import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex)

export default new Vuex.Store({
  plugins: [createPersistedState()],
  state: {
    todos:JSON.parse(localStorage.getItem("vuex") || '[]'),
    activeTab:"all",
  },
  getters:{
    activeTab:function(state){
      return state.activeTab;
    },
    filterTodos:function(state){
      if(state.activeTab === "all"){
        return state.todos;
      }else if(state.activeTab === "active"){
        //未完成 status=>false
        return state.todos.filter(v=>{
          return !v.status;
        })
      }else if(state.activeTab === "completed"){
        //完成态 status=>true
        return state.todos.filter(v=>{
          return v.status;
        })
      }
    },
    AllChecked:function(state){
      let checked = true;
      //遍历todos
      state.todos.map((v) => {
        if (!v.status) {
          checked = false;
        }
      });
      return checked;
    },
    countActive:function(state){
      let newTodos = state.todos.filter(v=>{
        return !v.status;
      });
      return newTodos.length;
    }
  },
  mutations: {
    addTodos:function(state,{payload}){
      state.todos.push(payload);
    },
    allCheck:function(state){
      //遍历todos所有元素
      state.todos.map((v) => {
        //将每个元素的状态status设置为true
        v.status = true;
      });
    },
    deleteTodos:function(state,index){
      state.todos.splice(index,1);
    },
    changeClick:function(state,activeTab){
      state.activeTab = activeTab;
    },
    delCompleted:function(state){
      let newTodos = state.todos.filter(v=>{
        return !v.status;
      });
      state.todos = newTodos;
    }
  },
  actions: {
  },
  modules: {
  }
})
